﻿#region References
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App_Code.Common;
using App_Code.Helpers;
using App_Code.Logic;
using App_Code.Objects;
using DotNetOpenAuth.OpenId.RelyingParty;
using Telerik.Web.UI;

#endregion

public partial class _Default : System.Web.UI.Page
{

    #region Properties
    public string ServerList
    {
        get
        {
            return SerializationHelper.SerializeToJSON(PageHelper.VisualCronSession.ServersDTO);
        }
    }

    #endregion

    #region Event Handlers
    protected void Page_Load(object sender, EventArgs e)
    {
        hdnSessionId.Value = HttpContext.Current.Session.SessionID;

        UpdateLoginInfo();
    }

    protected void LoadTasks(object sender, EventArgs e)
    {
        var jobId = Request.Form[hdnJobId.UniqueID];
        var userServerId = Request.Form[hdnUserServerId.UniqueID];

        // grid was invisible before because otherwise it will register itself on initial load which degrades performance
        RadGrid grid = (RadGrid)((Control)sender).Parent.FindControl("TaskGrid");
        grid.Visible = true;

        // add data to be bound into hidden field
        // this data should also be used to rebind data to grid when updates come from server
        var hidden = new HiddenField
                         {
                             Value = SerializationHelper.SerializeToJSON(GridDataSource.GetTasks(userServerId, jobId))
                         };

        ((Control)sender).Parent.Controls.Add(hidden);

        var hiddenJobId = new HiddenField {Value = String.Format("ownerJobId:{0}", jobId)};
        ((Control)sender).Parent.Controls.Add(hiddenJobId);

        // register script which will bind data from hidden filed into grid after it is initialized on client side
        ScriptManager.RegisterStartupScript(this,
            typeof(_Default),
            "UpdateTasksForJob" + jobId,
            String.Format("function pageLoad(){{TasksGrid_ApplyTasks('{0}','{1}','{2}','{3}');}}", userServerId, jobId, grid.ClientID, hidden.ClientID),
            true);
    }

    protected void ServerTree_OnNodeExpand(object sender, RadTreeNodeEventArgs e)
    {
        // we're using the tricky way to add row containing a RadGrid here:
        // step 1. we add a node, which template has UpdatePanel with RadGrid Visible=false
        // step 2. on client side we call _another_ update panel to update, this is because the update panel from this node won't update as it isn't
        // properly registered yet. It will register after another async postback
        // step 3. we finally call a method to make postback in newly added update panel inside of node, which makes RadGrid inside visible
        var node = new RadTreeNode("node");

        e.Node.Nodes.Add(node);

    }

    protected void JobGridSetVisible_OnClick(object sender, EventArgs e)
    {
        var ownerCtrl = ((Control) sender).Parent;

        // grid is invisible until now, because it only gets registered properly inside of Update Panel in async posback
        var grid = (RadGrid)ownerCtrl.FindControl("JobGrid");
        grid.Visible = true;

        // we added serverId to the value of root server node
        var serverId = ((RadTreeNode)ownerCtrl.NamingContainer).ParentNode.Value;

        var jobsList = GridDataSource.GetJobs(serverId);

        // fill grid with stub data - this will initialize necessary number of rows for us
        var stub = GridDataSource.GetJobsStub(jobsList.Count);
        grid.DataSource = stub;
        grid.PageSize = stub.Count;
        grid.DataBind();

        // fill hidden field with data which actually needs to be bound to grid
        // this data should would also be used to rebind data to grid when updates come from server
        var hidden = new HiddenField
                         {
                             Value = SerializationHelper.SerializeToJSON(jobsList)
                         };

        ((Control)sender).Parent.Controls.Add(hidden);

        // register script, which will bind data from hidden field into RadGrid after grid is initialized on client side
        ScriptManager.RegisterStartupScript(this,
            typeof(_Default),
            "UpdateJobsForServer" + serverId,
            String.Format("function pageLoad(){{JobsGrid_ApplyJobs('{0}','{1}','{2}');}}", serverId, grid.ClientID, hidden.ClientID),
            true);

    }

    protected void LogoutButton_OnClick(object sender, EventArgs e)
    {
        SessionLogic.SessionAuthenticationRemove(PageHelper.VisualCronSession);
        UpdateLoginInfo();

        // need to clear tree, because connections were cleared in SessionLogic.SessionAuthenticationRemove
        ServerTree.Nodes.Clear(); 
    }
    #endregion

    #region Private methods
    private void UpdateLoginInfo()
    {
        if (PageHelper.VisualCronSession.Profile != null)
        {
            labelUsername.Text = labelUsername.ToolTip = PageHelper.VisualCronSession.Profile.FriendlyOpenId;
            panelUserInfo.Visible = true;
        }
        else
        {
            panelLogin.Visible = true;
            panelUserInfo.Visible = false;
        }        
    }
    #endregion
    
}
